package com.hassean.we.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hassean.we.admin.common.constant.CommonConstant;
import com.hassean.we.admin.common.util.Query;
import com.hassean.we.admin.common.util.R;
import com.hassean.we.admin.common.web.BaseController;
import com.hassean.we.admin.model.entity.TbRescue;
import com.hassean.we.admin.model.entity.TbRescueTeam;
import com.hassean.we.admin.model.entity.TbTerminal;
import com.hassean.we.admin.model.entity.TbTerminalLocation;
import com.hassean.we.admin.service.TbRescueService;
import com.hassean.we.admin.service.TbRescueTeamService;
import com.hassean.we.admin.service.TbTerminalLocationService;
import com.hassean.we.admin.service.TbTerminalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yajun
 * @since 2019-03-29
 */
@Api(description = "救援任务接口")
@RestController
@RequestMapping("/tbRescue")
public class TbRescueController extends BaseController {
    @Autowired private TbRescueService tbRescueService;
    @Autowired private TbRescueTeamService tbRescueTeamService;
    @Autowired private TbTerminalService tbTerminalService;
    @Autowired private TbTerminalLocationService tbTerminalLocationService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return TbRescue
    */
    @ApiOperation(value = "通过ID查询救援任务" ,  notes="通过ID查询救援任务")
    @GetMapping("/{id}")
    public R<TbRescue> get(@PathVariable Long id) {
        return new R<>(tbRescueService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @ApiOperation(value = "分页查询救援任务" ,  notes="分页查询救援任务")
    @RequestMapping("/page")
    public R<Map<String, Object>>  getTbRescuePage(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        List< Map<String, Object>> resultList = new ArrayList<>();
        Map<String,Object>resultMap = new HashMap<>();
        Integer state = 0;
        if (params.get("state")!=null&&!(params.get("state")).equals("")){
             state = Integer.parseInt(params.get("state").toString());
            params.put("state", state);//状态条件查询.1未处理、2已处理
        }

        if (params.get("page")!=null&&!(params.get("page")).equals("")){
            Integer page = Integer.parseInt(params.get("page").toString());
            params.put("page",page);
        }else{
            Integer page = 1;
            params.put("page",page);
        }

        if (params.get("limit")!=null&&!(params.get("limit")).equals("")){
            Integer limit = Integer.parseInt(params.get("limit").toString());
            System.out.println("limit:"+limit);
        }else{
            Integer limit = 10;
            params.put("limit",limit);
        }
        EntityWrapper entity = new EntityWrapper<>();
        entity.orderDesc(Arrays.asList(new String [] {"rescue_id"}));//降序
        Page<TbRescue> page = tbRescueService.selectPage(new Query<>(params),entity);

        for (int i = 0; i <page.getRecords().size() ; i++) {
            Map<String, Object> map = new HashMap<>();

            map.put("rescueId", page.getRecords().get(i).getRescueId());
            map.put("seekHelpPhoneNumber", page.getRecords().get(i).getSeekHelpPhoneNumber());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sdf.format(page.getRecords().get(i).getAddTime());
            map.put("addTime",addTime);
            if(state==1){
                TbRescue tbResc =  tbRescueService.selectById(page.getRecords().get(i).getRescueId());
                tbResc.setState(2);
                tbRescueService.updateById(tbResc);

            }else{

            }
            map.put("state", page.getRecords().get(i).getState());
            map.put("content", page.getRecords().get(i).getContent());
            map.put("location", page.getRecords().get(i).getLocation());
            map.put("beam", page.getRecords().get(i).getBeam());
            map.put("status", page.getRecords().get(i).getStatus());
            map.put("remark", page.getRecords().get(i).getRemark());
            map.put("advanceText", page.getRecords().get(i).getAdvanceText());
            map.put("advanceDate", page.getRecords().get(i).getAdvanceDate());
            map.put("delFlag", page.getRecords().get(i).getDelFlag());
            map.put("longitude", page.getRecords().get(i).getLongitude());
            map.put("latitude", page.getRecords().get(i).getLatitude());

            Long rescueTeamId =page.getRecords().get(i).getRescueTeamId();//救援单位id
            Long seekHelpTerminalId = page.getRecords().get(i).getSeekHelpTerminalId();//求救终端ID
            if(rescueTeamId!=null){
                TbRescueTeam tbRescueTeam =  tbRescueTeamService.selectById(rescueTeamId);
                if(tbRescueTeam!=null){
                    map.put("tbRescueTeam",tbRescueTeam);
                }
            }
            if(seekHelpTerminalId!=null){
                TbTerminal tbTerminal =  tbTerminalService.selectById(seekHelpTerminalId);
                if(tbTerminal!=null){
                    map.put("tbTerminal",tbTerminal);
                    //获取经纬度

                    Long   terminal_id = tbTerminal.getTerminalId();
                    EntityWrapper entity_terminal_id = new EntityWrapper<>();
                    entity_terminal_id.eq("terminal_id",terminal_id);
                    map.put("longitude","");
                    map.put("latitude","");
                    TbTerminalLocation tbTerminalLocation =   tbTerminalLocationService.selectOne(entity_terminal_id);
                    if(tbTerminalLocation!=null){
                        ;
                        map.put("longitude",tbTerminalLocation.getLongitude());
                        map.put("latitude",tbTerminalLocation.getLatitude());

                    }


                }
            }
            resultList.add(map);
        }
        resultMap.put("total",page.getTotal());//总条数
        resultMap.put("size",page.getSize());//每一页多少条
        resultMap.put("pages",page.getPages());//总页数
        resultMap.put("curren",page.getCurrent());//起始页
        resultMap.put("resultList",resultList);
        return new R<>(resultMap);

    }

    /**
     *
     * 获取所有未读的救援新短息
     */
    @RequestMapping("/getTbRescue/total")
    public R<Map<String, Object>>  getTbRescue() {
        Map<String,Object>resultMap = new HashMap<>();
        EntityWrapper entity = new EntityWrapper<>();
        entity.eq("state",1);
        List<TbRescue> tbRescueList = tbRescueService.selectList(entity);
        if(!tbRescueList.isEmpty()){
           Integer total =  tbRescueList.size();
            resultMap.put("total",total);
        }else{
            resultMap.put("total",0);
        }

        return new R<>(resultMap);

    }



    /**
     * 添加
     * @param  tbRescue  实体
     * @return success/false
     */
    @ApiOperation(value = "添加救援任务" ,  notes="添加救援任务")
    @PostMapping("/add")
    public R<Boolean> add(@RequestBody TbRescue tbRescue) {
        try {
            if(tbRescue.getSeekHelpPhoneNumber()!=null){
                String phone = tbRescue.getSeekHelpPhoneNumber();
                List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(phone);
                if(!list.isEmpty()){
                    Long   terminalId =   (Long)list.get(0).get("terminal_id");
                    tbRescue.setSeekHelpTerminalId(terminalId);
                    return new R<>(tbRescueService.insert(tbRescue));
                }else{
                    System.out.println("此电话号码没有绑定终端机");
                }

            }
        }catch (Exception e){
           e.printStackTrace();
        }



        return new R<>(false);
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @ApiOperation(value = "删除救援任务" ,  notes="删除救援任务")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        TbRescue tbRescue = new TbRescue();
        tbRescue.setRescueId(id);
        tbRescue.setUpdateTime(new Date());
        tbRescue.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(tbRescueService.updateById(tbRescue));
    }

    /**
     * 编辑
     * @param  tbRescue  实体
     * @return success/false
     */
    @ApiOperation(value = "编辑救援任务" ,  notes="编辑救援任务")
    @PutMapping
    public R<Boolean> edit(@RequestBody TbRescue tbRescue) {
        tbRescue.setUpdateTime(new Date());
        return new R<>(tbRescueService.updateById(tbRescue));
    }
}
